#ifndef _process_pool_hpp__
#define _process_pool_hpp__

#include <iostream>
#include <cstdlib>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include "Task.hpp"

// 先描述
class Channel // 信道
{
public:
    Channel(int fd, pid_t id)
        : _wfd(fd), _subid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }
    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }
    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    ~Channel()
    {
    }
    int Fd() { return _wfd; }
    pid_t SubId() { return _subid; }
    std::string Name() { return _name; }

private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

// 再组织
class ChannelManager // 信道管理接口
{
public:
    ChannelManager() 
        :_next(0)
    {}
    void Insert(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
        // Channel c(wfd, subid);
        // _channels.push_back(c);
    }
    Channel &Select() //轮询选择一个信道
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void PrintChannels()
    {
        for (auto &ch : _channels)
        {
            std::cout << ch.Name() << std::endl;
        }
    }
    void CloseAll()
    {
        for(auto& ch : _channels)
        {
           ch.Close();
           std::cout<<"关闭了信道: "<<ch.Name()<<std::endl;
        }
    }
    void StopSubProcess()
    {
        for(auto& ch : _channels)
        {
           ch.Close();
           std::cout<<"关闭了信道: "<<ch.Name()<<std::endl;
        }
    }
    void WaitSubProcess()
    {
        for(auto& ch : _channels)
        {
           ch.Wait();
              std::cout<<"回收了子进程: "<<ch.SubId()<<std::endl;
        }
    }
    void CloseAndWait()
    {
        for(auto& ch : _channels)
        {
           ch.Close();
           std::cout<<"关闭了信道: "<<ch.Name()<<std::endl;
            ch.Wait();
              std::cout<<"回收了子进程: "<<ch.SubId()<<std::endl;
        }

        //解决方案1. 倒着关闭
        // for(int i = _channels.size()-1; i>=0; i--)
        // {
        //     _channels[i].Close();
        //     std::cout<<"关闭了信道: "<<_channels[i].Name()<<std::endl;
        //     _channels[i].Wait();
        //     std::cout<<"回收了子进程: "<<_channels[i].SubId()<<std::endl;
            
        // }
        //解决方案2. 真的让父进程一个人指向所有write端
    }
    ~ChannelManager() {}

private:
    std::vector<Channel> _channels;
    int _next;
};

const int gdefaultnum = 5; // 默认进程数量

class ProcessPool // 进程池
{
public:
    ProcessPool(int num)
        : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(UpLoad);
    }
    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程[" << getpid() << "]收到任务，任务码为: " << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else // 读失败
            {
                std::cout << "子进程读失败" << std::endl;
                break;
            }
        }
    }
    bool Start() // 父写子读
    {
        for (int i = 0; i < _process_num; ++i)
        {
            // 1.创建管道
            int fds[2] = {0};
            int n = pipe(fds);
            if (n < 0)
                return false;

            // 2.创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                sleep(1);
                // child
                std::cout<<"##################\n"<<"第"<<i<<"个子进程启动"<<std::endl;
                _cm.PrintChannels();
                std::cout<<"##################"<<std::endl;
                _cm.CloseAll();
                // 3.关闭写端，形成单向通信
                close(fds[1]);
                Work(fds[0]); //??
                close(fds[0]);
                exit(0);
            }
            else
            {
                sleep(1);
                // father
                // 3.关闭读端，形成单向通信
                close(fds[0]);
                _cm.Insert(fds[1], subid);
            }
        }
        return true;
    }
    void Debug()
    {
        _cm.PrintChannels();
    }
    void Run()
    {
        // 1.选择一个任务
        int taskcode = _tm.Code();

        // 2.选择一个信道，负载均衡的选择一个子进程，完成任务
        auto &c = _cm.Select();
        std::cout << "选择了一个子进程" << c.Name() << std::endl;
        // 3.发送任务
        c.Send(taskcode);
        std::cout << "发送了一个任务码: " << taskcode << std::endl;
    }
    void Stop()
    {
    //    // 关闭所有写端，子进程会退出
    //     _cm.StopSubProcess();
    //    //回收子进程
    //     _cm.WaitSubProcess();
        _cm.CloseAndWait();
    }
    ~ProcessPool()
    {
    }

private:
    ChannelManager _cm;
    int _process_num; // 进程数量
    TaskManager _tm;
};

#endif // _process_pool_hpp__